import inquirer
import requests
from code.util import clear_util


def get_user_selection(page_name, options):
    """
    显示多选列表，让用户选择。
    :param page_name: 当前页面名称
    :param options: 当前页面的可选项列表
    :return: 用户选择的项
    """
    questions = [
        inquirer.Checkbox(
            'choices',
            message=f"当前是 {page_name}，请选择选项（使用空格选择，回车确认）",
            choices=options
        )
    ]
    answers = inquirer.prompt(questions)
    return answers.get('choices', [])

def navigate_pages():
    """
    控制页面切换并记录用户的选择。
    :return: 所有页面的用户选择的合并结果
    """
    pages = {
        "首页": ["跳转到页面1", "跳转到页面2", "完成选择"],
        "页面1": ["选项1", "选项2", "选项3", "选项4"],
        "页面2": ["选项5", "选项6", "选项7", "选项8"],
        "完成选择": [],
        "退出程序": []
    }

    selected_items = []

    while True:
        next_page_question = [
            inquirer.List(
                'next_action',
                message="请选择下一步操作",
                choices=pages,
                carousel=True,
            )
        ]
        answers = inquirer.prompt(next_page_question)
        clear_util.clear_screen()
        print(f"你选择了: {answers['next_action']}")
        next_action = answers['next_action']


        if next_action == "完成选择":
            break
        if next_action == "退出程序":
            selected_items = []
            break
        elif next_action == "页面1":
            current_page = "页面1"
            options = pages[current_page]
            page_selection = get_user_selection(current_page, options)
            selected_items.extend(x for x in page_selection if x not in selected_items)
        elif next_action == "页面2":
            current_page = "页面2"
            options = pages[current_page]
            page_selection = get_user_selection(current_page, options)
            selected_items.extend(x for x in page_selection if x not in selected_items)


        clear_util.clear_screen()
        print(f"当前已选择：{selected_items}")

    return selected_items

def send_to_http_endpoint(selected_items, url):
    """
    将选择的内容发送到指定 HTTP 接口。
    :param selected_items: 用户选择的内容
    :param url: HTTP 接口地址
    :return: 接口响应
    """
    data = {'selected_items': selected_items}
    try:
        response = requests.post(url, json=data)
        response.raise_for_status()
        return response.json()
    except requests.RequestException as e:
        return {"error": str(e)}
